/**
 * Created by Tuffy on 16/6/6.
 */
'use strict';

adminCtrl

    .controller('WayBillPreviewCtrl', ['$rootScope', '$scope', '$state', '$modal', 'AreaService', 'CompanyService', 'WaybillService', function ($rootScope, $scope, $state, $modal, AreaService, CompanyService, WaybillService) {

        // 提车 交车运输方式
        $scope.trans1 = [{
            code: 0,
            name: '代驾'
        }, {
            code: 1,
            name: '小板'
        }];

        // 长途运输方式
        $scope.trans2 = [{
            code: 0,
            name: '小板'
        }, {
            code: 1,
            name: '大板'
        }];

        $scope.page = {
            pageNo: 1,
            totalPage: 0
        };

        // 查询条件
        $scope.waybillInfo = {
            departProvinceCode: '',
            departCityCode: '',
            departCountyCode: '',
            departAddr: '',
            receiptProvinceCode: '',
            receiptCityCode: '',
            receiptCountyCode: '',
            receiptAddr: '',
            cost: '',
            shipmentDate: '',
            arriveDate: '',
            bidderId: '',
            isExtract: false,
            isLongHaul: false,
            isDelivery: false,
            extractWay: '',
            longHaulWay: '',
            deliveryWay: '',
            sorderIds: $rootScope.sorderIds,
            departDriverName: '',
            departDriverPhone: '',
            receiptDriverName: '',
            receiptDriverPhone: '',
            waybillType: '',
            refCost: $rootScope.sorderCost,
            isVeneer: $rootScope.checkOrder[0].isVeneer
        }

        // 查询条件区域数据
        $scope.loadProvince = [];

        // 加载发车市
        $scope.departCity = [];

        // 加载发车区县
        $scope.departCounty = [];

        // 加载到达市
        $scope.receiptCity = [];

        // 加载到达区县
        $scope.receiptCounty = [];

        // 加载承运商
        $scope.carrierList = [];

        // 设置模态窗口
        var myOtherModal = $modal({
            scope: $scope,
            title: '选择承运商',
            placement: 'center',
            templateUrl: $rootScope.Context.path + '/templates/components/carrier-view.html',
            show: false
        });

        // 加载省数据
        function loadProvince() {
            AreaService.loadProvince()
                .success(function (result) {
                    if (result.success) {
                        $scope.loadProvince = result.data;
                        // 初始化数据
                        initData();
                    }
                });
        };
        // 根据省编码查询发车市
        $scope.loadDepartCity = function () {
            AreaService.loadCityByCode($scope.waybillInfo.departProvinceCode)
                .success(function (result) {
                    if (result.success) {
                        $scope.departCity = result.data;
                    }
                });
        };
        // 根据省编码查询发车区县
        $scope.loadDepartCounty = function () {
            AreaService.loadCountyByCode($scope.waybillInfo.departCityCode)
                .success(function (result) {
                    if (result.success) {
                        $scope.departCounty = result.data;
                    }
                });
        };
        // 根据省编码查询收车市
        $scope.loadReceiptCity = function () {
            AreaService.loadCityByCode($scope.waybillInfo.receiptProvinceCode)
                .success(function (result) {
                    if (result.success) {
                        $scope.receiptCity = result.data;
                    }
                });
        };
        // 根据省编码查询收车区县
        $scope.loadReceiptCounty = function () {
            AreaService.loadCountyByCode($scope.waybillInfo.receiptCityCode)
                .success(function (result) {
                    if (result.success) {
                        $scope.receiptCounty = result.data;
                    }
                });
        };

        // 接单
        $scope.robOrder = function () {
            if (validate()) {
                // 校验非空
                $scope.waybillInfo.waybillType = Tools.getWayBillType.getBidself();
                $scope.waybillInfo.shipmentDate = $scope.waybillInfo.shipmentDate == '' ? "" : typeof($scope.waybillInfo.shipmentDate) == 'string' ? $scope.waybillInfo.shipmentDate : $scope.waybillInfo.shipmentDate.format("yyyy-MM-dd HH:mm:ss");
                $scope.waybillInfo.arriveDate = $scope.waybillInfo.arriveDate == '' ? "" : typeof($scope.waybillInfo.arriveDate) == 'string' ? $scope.waybillInfo.arriveDate : $scope.waybillInfo.arriveDate.format("yyyy-MM-dd HH:mm:ss");
                $scope.waybillInfo.sorderIds = $scope.waybillInfo.sorderIds.toString();
                if (!$scope.waybillInfo.isDelivery && !$scope.waybillInfo.isExtract && !$scope.waybillInfo.isLongHaul) {
                    $rootScope.hycadmin.toast({
                        title: '至少选择一种运单类型',
                        timeOut: 3000
                    });
                    return
                }
                $rootScope.hycadmin.loading({
                    title: '数据处理中...'
                });
                WaybillService.createWayBill($scope.waybillInfo)
                    .success(function (result) {
                        if (result.success) {
                            $state.go('split-order');
                        } else {
                            $rootScope.hycadmin.toast({
                                title: result.message,
                                timeOut: 3000
                            });
                        }
                        clearCheckOrder();
                    }).finally(function () {
                    $rootScope.hycadmin.loading.hide();
                });
            }
        };

        // 清空选择的服务订单
        function clearCheckOrder() {
            // 已选择订单列
            $rootScope.checkOrder = [];
            // 合单服务订单IDS
            $rootScope.sorderIds = [];
            // 合单服务订单总价
            $rootScope.sorderCost = 0;
        }

        // 派单
        $scope.sendOrder = function () {
            $scope.waybillInfo.waybillType = Tools.getWayBillType.getAssing();
            // 校验非空
            if (validate()) {
                if (!$scope.waybillInfo.isDelivery && !$scope.waybillInfo.isExtract && !$scope.waybillInfo.isLongHaul) {
                    $rootScope.hycadmin.toast({
                        title: '至少选择一种运单类型',
                        timeOut: 3000
                    });
                    return
                }
                myOtherModal.$promise.then(myOtherModal.show);
                // 初始化承运商
                loadCarrier();
            }
        }

        function validate() {
            var flg = true;
            if ($scope.waybillInfo.shipmentDate == '') {
                $rootScope.hycadmin.toast({
                    title: '起运日期不能为空',
                    timeOut: 3000
                });
                flg = false;
            } else if ($scope.waybillInfo.arriveDate == '') {
                $rootScope.hycadmin.toast({
                    title: '到达日期不能为空',
                    timeOut: 3000
                });
                flg = false;
            } else if ((+$scope.waybillInfo.shipmentDate) - (+$scope.waybillInfo.arriveDate) > 0) {
                $rootScope.hycadmin.toast({
                    title: '起运日期不能大于到达日期',
                    timeOut: 3000
                });
                flg = false;
            } else if ($scope.waybillInfo.departProvinceCode == '') {
                $rootScope.hycadmin.toast({
                    title: '起运地省不能为空',
                    timeOut: 3000
                });
                flg = false;
            } else if ($scope.waybillInfo.departCityCode == '') {
                $rootScope.hycadmin.toast({
                    title: '起运地市不能为空',
                    timeOut: 3000
                });
                flg = false;
            } else if ($scope.waybillInfo.departCountyCode == '') {
                $rootScope.hycadmin.toast({
                    title: '起运地区县不能为空',
                    timeOut: 3000
                });
                flg = false;
            } else if ($scope.waybillInfo.receiptProvinceCode == '') {
                $rootScope.hycadmin.toast({
                    title: '到达地省不能为空',
                    timeOut: 3000
                });
                flg = false;
            } else if ($scope.waybillInfo.receiptCityCode == '') {
                $rootScope.hycadmin.toast({
                    title: '到达地市不能为空',
                    timeOut: 3000
                });
                flg = false;
            } else if ($scope.waybillInfo.receiptCountyCode == '') {
                $rootScope.hycadmin.toast({
                    title: '到达地区县不能为空',
                    timeOut: 3000
                });
                flg = false;
            } else if ($scope.waybillInfo.cost == '') {
                $rootScope.hycadmin.toast({
                    title: '运单价格不能为空',
                    timeOut: 3000
                });
                flg = false;
            } else if ($scope.waybillInfo.departDriverName == '') {
                $rootScope.hycadmin.toast({
                    title: '提车联系人不能为空',
                    timeOut: 3000
                });
                flg = false;
            } else if ($scope.waybillInfo.departDriverPhone == '') {
                $rootScope.hycadmin.toast({
                    title: '提车联系人电话不能为空',
                    timeOut: 3000
                });
                flg = false;
            } else if ($scope.waybillInfo.receiptDriverName == '') {
                $rootScope.hycadmin.toast({
                    title: '交车联系人不能为空',
                    timeOut: 3000
                });
                flg = false;
            } else if ($scope.waybillInfo.receiptDriverPhone == '') {
                $rootScope.hycadmin.toast({
                    title: '交车联系人电话不能为空',
                    timeOut: 3000
                });
                flg = false;
            } else if ($scope.waybillInfo.departAddr == '') {
                $rootScope.hycadmin.toast({
                    title: '起运地详细地址不能为空',
                    timeOut: 3000
                });
                flg = false;
            } else if ($scope.waybillInfo.receiptAddr == '') {
                $rootScope.hycadmin.toast({
                    title: '目的地详细地址不能为空',
                    timeOut: 3000
                });
                flg = false;
            } else if (!Tools.isMobileNo($scope.waybillInfo.departDriverPhone)) {
                $rootScope.hycadmin.toast({
                    title: '提车联系人电话格式错误',
                    timeOut: 3000
                });
                flg = false;
            } else if ($scope.waybillInfo.departDriverPhone.length > 11 || $scope.waybillInfo.departDriverPhone.length < 11) {
                $rootScope.hycadmin.toast({
                    title: '提车联系人电话格式错误',
                    timeOut: 3000
                });
                flg = false;
            } else if (!Tools.isMobileNo($scope.waybillInfo.receiptDriverPhone)) {
                $rootScope.hycadmin.toast({
                    title: '交车联系人电话格式错误',
                    timeOut: 3000
                });
                flg = false;
            } else if ($scope.waybillInfo.receiptDriverPhone.length > 11 || $scope.waybillInfo.receiptDriverPhone.length < 11) {
                $rootScope.hycadmin.toast({
                    title: '交车联系人电话格式错误',
                    timeOut: 3000
                });
                flg = false;
            }
            if ($scope.waybillInfo.isDelivery) {
                if ($scope.waybillInfo.deliveryWay === '') {
                    $rootScope.hycadmin.toast({
                        title: '选择交车运单时运输方式不能为空',
                        timeOut: 3000
                    });
                    flg = false;
                }
            } else {
                $scope.waybillInfo.deliveryWay = '';
            }
            if ($scope.waybillInfo.isLongHaul) {
                if ($scope.waybillInfo.longHaulWay === '') {
                    $rootScope.hycadmin.toast({
                        title: '选择长途运输时运输方式不能为空',
                        timeOut: 3000
                    });
                    flg = false;
                }
            } else {
                $scope.waybillInfo.longHaulWay = '';
            }
            if ($scope.waybillInfo.isExtract) {
                if ($scope.waybillInfo.extractWay === '') {
                    $rootScope.hycadmin.toast({
                        title: '选择提车时运输方式不能为空',
                        timeOut: 3000
                    });
                    flg = false;
                }
            } else {
                $scope.waybillInfo.extractWay = '';
            }
            return flg;
        }

        // 加载承运商
        function loadCarrier() {
            CompanyService.carrierList({
                truckType: 0
            }).success(function (result) {
                if (result.success) {
                    $scope.carrierList = result.data;
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
        }

        // 创建运单
        $scope.createWaybill = function () {
            if ($scope.waybillInfo.bidderId == null || !Tools.isNumber($scope.waybillInfo.bidderId)) {
                $scope.errorMessage = '请选择承运商';
                return;
            }
            $scope.waybillInfo.shipmentDate = $scope.waybillInfo.shipmentDate == '' ? "" : $scope.waybillInfo.shipmentDate.format("yyyy-MM-dd HH:mm:ss");
            $scope.waybillInfo.arriveDate = $scope.waybillInfo.arriveDate == '' ? "" : $scope.waybillInfo.arriveDate.format("yyyy-MM-dd HH:mm:ss");
            $scope.waybillInfo.sorderIds = $scope.waybillInfo.sorderIds.toString();
            $rootScope.hycadmin.loading({
                title: '数据处理中...'
            });
            // 校验非空
            WaybillService.createWayBill($scope.waybillInfo)
                .success(function (result) {
                    if (result.success) {
                        myOtherModal.$promise.then(myOtherModal.hide);
                        $state.go('split-order');
                    } else {
                        $rootScope.hycadmin.toast({
                            title: result.message,
                            timeOut: 3000
                        });
                    }
                    clearCheckOrder();
                }).finally(function () {
                $rootScope.hycadmin.loading.hide();
            });
        };

        // 计算参考价格
        $scope.calculate = function () {
            //angular.forEach($scope.checkOrder, function(item) {
            //    $rootScope.sorderCost += (+item.refCost);
            //});
            WaybillService.proposedPrice($scope.waybillInfo.departCountyCode, $scope.waybillInfo.departAddr, $scope.waybillInfo.receiptCountyCode, $scope.waybillInfo.receiptAddr, $scope.waybillInfo.arriveDate == '' ? "" : typeof($scope.waybillInfo.arriveDate) == 'string' ? $scope.waybillInfo.arriveDate : $scope.waybillInfo.arriveDate.format("yyyy-MM-dd HH:mm:ss"), JSON.stringify($rootScope.sorderIds)
            ).success(function (result) {
                if (result.success) {
                    $rootScope.sorderCost = result.data;
                    $scope.waybillInfo.refCost = result.data;
                }
            });
        };

        // 移除服务订单
        $scope.removeServiceOrder = function (order) {
            if ($rootScope.checkOrder.length == 1) {
                $rootScope.hycadmin.toast({
                    title: '服务订单不能为空',
                    timeOut: 3000
                });
                return;
            }
            for (var i = 0; i < $rootScope.checkOrder.length; i++) {
                var item = $rootScope.checkOrder[i];
                if (item.id == order.id) {
                    $rootScope.checkOrder.splice(i, 1);
                    initData();
                    break;
                }
            }
            for (var i = 0; i < $rootScope.sorderIds.length; i++) {
                var item = $rootScope.sorderIds[i];
                if (item == order.id) {
                    $rootScope.sorderIds.splice(i, 1);
                    break;
                }
            }
            // 计算参考价格
            $scope.calculate();
        };

        function initData() {
            if ($rootScope.checkOrder.length >= 1) {
                var orderInfo = $rootScope.checkOrder[0];
                $scope.waybillInfo.departProvinceCode = orderInfo.departProvinceCode;
                $scope.waybillInfo.departCityCode = orderInfo.departCityCode;
                $scope.waybillInfo.departCountyCode = orderInfo.departCountyCode;
                $scope.waybillInfo.departAddr = orderInfo.departAddr;
                $scope.waybillInfo.receiptProvinceCode = orderInfo.receiptProvinceCode;
                $scope.waybillInfo.receiptCityCode = orderInfo.receiptCityCode;
                $scope.waybillInfo.receiptCountyCode = orderInfo.receiptCountyCode;
                $scope.waybillInfo.receiptAddr = orderInfo.receiptAddr;
                $scope.waybillInfo.shipmentDate = new Date();
                if (orderInfo.arriveDate != null && orderInfo.arriveDate != '') {
                    $scope.waybillInfo.arriveDate = new Date(orderInfo.arriveDate);
                } else {
                    $scope.waybillInfo.arriveDate = '';
                }
                $scope.waybillInfo.departDriverName = orderInfo.departContact;
                $scope.waybillInfo.departDriverPhone = orderInfo.departPhone;
                $scope.waybillInfo.receiptDriverName = orderInfo.receiptContact;
                $scope.waybillInfo.receiptDriverPhone = orderInfo.receiptPhone;
                $scope.loadDepartCity();
                $scope.loadDepartCounty();
                $scope.loadReceiptCity();
                $scope.loadReceiptCounty();
            }
        }

        // 加载省数据
        loadProvince();
    }])

    .controller('WayBillListCtrl', ['$rootScope', '$scope', '$state', '$tooltip', '$typeahead', '$modal', '$timeout', 'FileUploader', 'QiniuService', 'AreaService', 'WaybillService', 'WayBillContactsService', 'WaybillTrailService', 'WaybillAttachService', function ($rootScope, $scope, $state, $tooltip, $typeahead, $modal, $timeout, FileUploader, QiniuService, AreaService, WaybillService, WayBillContactsService, WaybillTrailService, WaybillAttachService) {
        // 查询条件
        $scope.waybillInfo = {
            departProvinceCode: '',
            departCityCode: '',
            departCountyCode: '',
            receiptProvinceCode: '',
            receiptCityCode: '',
            receiptCountyCode: '',
            waybillCode: '',
            status: '',
            payStatus: '',
            beginDateTime: '',
            endDateTime: '',
            orderCode: ''
        };
        // 交接单联系人对象
        $scope.contactsObj = {
            id: '',
            waybillId: '',
            type: '',
            contact: '',
            idno: '',
            phone: '',
            licenseNumner: '',
            updateTime: '',
            createTime: ''
        };
        // 在途信息对象
        $scope.waybillTrailObj = {
            id: '',
            waybillId: '',
            latitude: '',
            longitude: '',
            cityCode: '',
            cityName: '',
            provinceCode: '',
            provinceName: '',
            countyCode: '',
            countyName: '',
            addr: '',
            updateTime: ''
        };

        // 运单附件对象
        $scope.waybillAttach = {
            id: '',
            userId: '',
            image: '',
            picKey: '',
            category: '',
            type: ''
        };

        // 查询条件区域数据
        $scope.loadProvince = [];

        // 加载发车市
        $scope.departCity = [];

        // 加载到达市
        $scope.receiptCity = [];

        // 加载物流市
        $scope.trailCity = [];

        // 运单列表
        $scope.wayBillList = [];

        // 在途信息列表
        $scope.waybillTrail = [];

        // 运单附件
        $scope.attach = [];

        // 提车安排模态窗口
        var liftModal = $modal({
            scope: $scope,
            title: '提车安排',
            placement: 'center',
            templateUrl: $rootScope.Context.path + '/templates/components/lift-view.html',
            show: false
        });

        // 在途模态窗口
        var routeModal = $modal({
            scope: $scope,
            title: '在途上报',
            placement: 'center',
            templateUrl: $rootScope.Context.path + '/templates/components/route-view.html',
            show: false
        });

        // 查看在途模态窗口
        var seeRouteModal = $modal({
            scope: $scope,
            title: '在途信息',
            placement: 'center',
            templateUrl: $rootScope.Context.path + '/templates/components/see-route-view.html',
            show: false
        });

        // 交车模态窗口
        var dealModal = $modal({
            scope: $scope,
            title: '交车安排',
            placement: 'center',
            templateUrl: $rootScope.Context.path + '/templates/components/deal-view.html',
            show: false
        });

        // 发车模态窗口
        var departModal = $modal({
            scope: $scope,
            title: '发车安排',
            placement: 'center',
            templateUrl: $rootScope.Context.path + '/templates/components/depart-view.html',
            show: false
        });

        // 提车审核模态窗口
        var liftAuditModal = $modal({
            scope: $scope,
            title: '提车审核',
            placement: 'center',
            templateUrl: $rootScope.Context.path + '/templates/components/lift-audit-view.html',
            show: false
        });

        // 交车审核模态窗口
        var dealAuditModal = $modal({
            scope: $scope,
            title: '交车审核',
            placement: 'center',
            templateUrl: $rootScope.Context.path + '/templates/components/deal-audit-view.html',
            show: false
        });

        //上传提车照片
        var liftPicModal = $modal({
            scope: $scope,
            title: '上传提车照片',
            placement: 'center',
            templateUrl: $rootScope.Context.path + '/templates/components/lift-pic-view.html',
            show: false
        });

        //上传交车照片
        var dealPicModal = $modal({
            scope: $scope,
            title: '上传交车照片',
            placement: 'center',
            templateUrl: $rootScope.Context.path + '/templates/components/deal-pic-view.html',
            show: false
        });


        // 当前对象
        $scope.userTruckObj = {
            pageNo: 1,
            pageSize: 10,
            loadMore: function ($event, pageNo) {
                this.pageNo = pageNo;
                if ((this.pageNo > $scope.page.totalPage)) {
                    $event.stopPropagation();
                    this.pageNo = $scope.page.totalPage;
                    return;
                } else if (this.pageNo < 1) {
                    $event.stopPropagation();
                    this.pageNo = 1;
                    return;
                }
                $scope.loadData();
            }
        };

        // 初始化数据列表
        $scope.loadData = function (params) {
            if ('query' === params) {
                $scope.userTruckObj.pageNo = 1;
                $scope.userTruckObj.pageSize = 10;
                $scope.page.pageNo = 1;
                $scope.page.totalPage = 0;
            }
            if ($scope.waybillInfo.beginDateTime != null && $scope.waybillInfo.beginDateTime != null) {
                if ((+$scope.waybillInfo.endDateTime) - (+$scope.waybillInfo.beginDateTime) < 0) {
                    $rootScope.hycadmin.toast({
                        title: '调度开始时间不能大于结束时间',
                        timeOut: 3000
                    });
                    return;
                }
            }
            WaybillService.loadWayBill({
                pageNo: $scope.userTruckObj.pageNo,
                pageSize: $scope.userTruckObj.pageSize,
                departProvinceCode: $scope.waybillInfo.departProvinceCode,
                departCityCode: $scope.waybillInfo.departCityCode,
                departCountyCode: $scope.waybillInfo.departCountyCode,
                receiptProvinceCode: $scope.waybillInfo.receiptProvinceCode,
                receiptCityCode: $scope.waybillInfo.receiptCityCode,
                receiptCountyCode: $scope.waybillInfo.receiptCountyCode,
                waybillCode: $scope.waybillInfo.waybillCode,
                status: $scope.waybillInfo.status,
                payStatus: $scope.waybillInfo.payStatus,
                beginDateTime: $scope.waybillInfo.beginDateTime == '' ? "" : typeof ($scope.waybillInfo.beginDateTime) == 'string' ? $scope.waybillInfo.beginDateTime : $scope.waybillInfo.beginDateTime.format("yyyy-MM-dd 00:00:00"),
                endDateTime: $scope.waybillInfo.endDateTime == '' ? "" : typeof ($scope.waybillInfo.endDateTime) == 'string' ? $scope.waybillInfo.endDateTime : $scope.waybillInfo.endDateTime.format("yyyy-MM-dd 23:59:59"),
                isVeneer: false,
                orderCode: $scope.waybillInfo.orderCode
            }).success(function (result) {
                if (result.success) {
                    $scope.wayBillList = result.data.waybillVo;
                    angular.forEach($scope.wayBillList, function (item) {
                        item.statusText = Tools.getWaybillStatusText(item.status);
                        item.payStatusText = Tools.getWaybillPayStatusText(item.payStatus);
                    })
                    $scope.page = result.data.page;
                    buildPage();
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
        }

        // 清空查询条件
        $scope.clearQuery = function () {
            $scope.waybillInfo = {
                departProvinceCode: '',
                departCityCode: '',
                departCountyCode: '',
                receiptProvinceCode: '',
                receiptCityCode: '',
                receiptCountyCode: '',
                waybillCode: '',
                status: '',
                payStatus: '',
                beginDateTime: '',
                endDateTime: '',
                orderCode: ''
            };
            $scope.loadData('query');
        };
        function cleanTrail() {
            $scope.waybillTrailObj = {
                latitude: '',
                longitude: '',
                cityCode: '',
                cityName: '',
                provinceCode: '',
                provinceName: '',
                countyCode: '',
                countyName: '',
                addr: '',
                updateTime: ''
            }
            $scope.loadData('load');
        }

        // 清空附件对象
        function cleanAttach() {
            $scope.waybillAttach = {
                id: '',
                userId: '',
                image: '',
                picKey: '',
                category: '',
                type: ''
            }
        }

        function buildPage() {
            $scope.item = [];
            var end = ($scope.page.totalPage - $scope.userTruckObj.pageNo) > 5 ? ($scope.userTruckObj.pageNo == 1 ? (parseInt($scope.userTruckObj.pageNo) + 5) : (parseInt($scope.userTruckObj.pageNo) + 5)) : $scope.page.totalPage;
            var start = $scope.userTruckObj.pageNo > 5 ? ($scope.userTruckObj.pageNo == 1 ? (parseInt($scope.userTruckObj.pageNo) - 5) : (parseInt($scope.userTruckObj.pageNo) - 5)) : 1;
            for (var i = start; i <= end; i++) {
                $scope.item.push(i);
            }
            // 调整行高度
            $scope.repeatFinish();
        };

        // 加载省数据
        function loadProvince() {
            AreaService.loadProvince()
                .success(function (result) {
                    if (result.success) {
                        $scope.loadProvince = result.data;
                    }
                });
        };
        // 根据省编码查询发车市
        $scope.loadDepartCity = function () {
            AreaService.loadCityByCode($scope.waybillInfo.departProvinceCode)
                .success(function (result) {
                    if (result.success) {
                        $scope.departCity = result.data;
                    }
                });
        };
        // 根据市编码查询发车区县
        $scope.loadDepartCounty = function () {
            AreaService.loadCountyByCode($scope.waybillInfo.departCityCode)
                .success(function (result) {
                    if (result.success) {
                        $scope.departCounty = result.data;
                    }
                });
        };
        // 根据省编码查询收车市
        $scope.loadReceiptCity = function () {
            AreaService.loadCityByCode($scope.waybillInfo.receiptProvinceCode)
                .success(function (result) {
                    if (result.success) {
                        $scope.receiptCity = result.data;
                    }
                });
        };
        // 根据市编码查询收车区县
        $scope.loadReceiptCounty = function () {
            AreaService.loadCountyByCode($scope.waybillInfo.receiptCityCode)
                .success(function (result) {
                    if (result.success) {
                        $scope.receiptCounty = result.data;
                    }
                });
        };

        // 根据省编码物流上报市
        $scope.loadTrailCity = function () {
            AreaService.loadCityByCode($scope.waybillTrailObj.provinceCode)
                .success(function (result) {
                    if (result.success) {
                        $scope.trailCity = result.data;
                    }
                });
        };

        // 根据省编码物流上报市
        $scope.loadTrailCounty = function () {
            AreaService.loadCountyByCode($scope.waybillTrailObj.cityCode)
                .success(function (result) {
                    if (result.success) {
                        $scope.trailCounty = result.data;
                    }
                });
        };

        // 提车窗口
        $scope.liftModel = function (waybillId, type) {
            WayBillContactsService.selectContacts({
                waybillId: waybillId,
                type: type
            }).success(function (result) {
                if (result.success) {
                    clearContact();
                    if (result.data != null) {
                        $scope.contactsObj = result.data;
                    }
                    $scope.contactsObj.waybillId = waybillId;
                    liftModal.$promise.then(liftModal.show);
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
        };
        // 提车审核窗口
        $scope.liftAuditModel = function (waybillId) {
            WaybillService.selectWaybillContact({
                id: waybillId,
                attachType: Tools.getAttachType.getReceipt(),
                type: Tools.getContactType.getDepartPerson()
            }).success(function (result) {
                if (result.success) {
                    $scope.contactsObj = result.data;
                    liftAuditModal.$promise.then(liftAuditModal.show);
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
        };
        // 提车审核
        $scope.liftAudit = function () {
            WaybillService.liftAudit({
                waybillId: $scope.contactsObj.id
            }).success(function (result) {
                if (result.success) {
                    $scope.loadData('load');
                    liftAuditModal.$promise.then(liftAuditModal.hide);
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
        };

        // 提车驳回
        $scope.liftAuditRebut = function () {
            WaybillService.liftAuditRebut({
                waybillId: $scope.contactsObj.id
            }).success(function (result) {
                if (result.success) {
                    $scope.loadData('load');
                    liftAuditModal.$promise.then(liftAuditModal.hide);
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
        };

        // 运单ID
        $scope.waybillID = '';

        // 上报提车照片窗口
        $scope.liftPicModel = function (waybill) {
            $scope.uploadImgs();
            $scope.waybillLiftCode = waybill.waybillCode;
            WayBillContactsService.selectContacts({
                waybillId: waybill.id,
                type: Tools.getContactType.getDepartPerson()
            }).success(function (result) {
                if (result.success) {
                    if (result.data == null) {
                        $rootScope.hycadmin.toast({
                            title: '请先上报提车安排',
                            timeOut: 3000
                        });
                        return;
                    } else {
                        $scope.waybillID = waybill.id;
                        WaybillService.selectWaybillContact({
                            id: waybill.id,
                            attachType: Tools.getAttachType.getReceipt(),
                            type: Tools.getContactType.getDepartPerson()
                        }).success(function (result) {
                            if (result.success) {
                                if (result.data != null) {
                                    $scope.contactsObj = result.data;
                                    if ($scope.contactsObj != null) {
                                        $scope.attach = $scope.contactsObj.attachs;
                                        if ($scope.attach != null && $scope.attach.length > 0) {
                                            angular.forEach($scope.attach, function (item) {
                                                item.picHtml = '<img src="' + item.picKey + '" style="width: 194px; height: 180px; z-index: 0;" onerror="Tools.onLoadImgErrorCallback(this, \'/image/bill-default-logo.png\')">';
                                            });
                                            $scope.bool = false;
                                        } else {
                                            for (var i = 0; i < 2; i++) {
                                                $scope.waybillAttach.category = Tools.getAttachType.getReceipt();
                                                if (i == 0) {
                                                    $scope.waybillAttach.type = Tools.getAttachTypeEnum.getReceiptBill();
                                                } else {
                                                    $scope.waybillAttach.type = Tools.getAttachTypeEnum.getReceiptPhoto();
                                                }
                                                $scope.waybillAttach.userId = 0;
                                                $scope.waybillAttach.picHtml = '<img src="' + $scope.waybillAttach.picKey + '" style="width: 194px; height: 180px; z-index: 0;" onerror="Tools.onLoadImgErrorCallback(this, \'/image/+.png\')">';
                                                $scope.attach.push($scope.waybillAttach);
                                                // 清空对象
                                                cleanAttach();
                                            }
                                            $scope.bool = true;
                                        }
                                    }
                                    liftPicModal.$promise.then(liftPicModal.show);
                                }
                            } else {
                                $rootScope.hycadmin.toast({
                                    title: result.message,
                                    timeOut: 3000
                                });
                            }
                        });
                    }
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
        };

        // 发车窗口
        $scope.departModel = function (waybillId, type) {
            WayBillContactsService.selectContacts({
                waybillId: waybillId,
                type: type
            }).success(function (result) {
                if (result.success) {
                    clearContact();
                    if (result.data != null) {
                        $scope.contactsObj = result.data;
                    }
                    $scope.contactsObj.waybillId = waybillId;
                    departModal.$promise.then(departModal.show);
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
        };

        // 在途上报窗口
        $scope.routeModel = function (waybillId) {
            WaybillTrailService.selectByWaybillId({
                waybillId: waybillId
            }).success(function (result) {
                if (result.success) {
                    if (result.data != null) {
                        $scope.waybillTrail = result.data;
                    } else {
                        $scope.waybillTrail = [];
                    }
                    $scope.waybillTrailObj.waybillId = waybillId;
                    routeModal.$promise.then(routeModal.show);
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
        };
        // 查看在途上报窗口
        $scope.seeRouteModel = function (waybillId) {
            WaybillTrailService.selectByWaybillId({
                waybillId: waybillId
            }).success(function (result) {
                if (result.success) {
                    if (result.data != null) {
                        $scope.waybillTrail = result.data;
                    } else {
                        $scope.waybillTrail = [];
                    }
                    $scope.waybillTrailObj.waybillId = waybillId;
                    seeRouteModal.$promise.then(seeRouteModal.show);
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
        };
        // 新增在途信息
        $scope.saveWaybillTrail = function () {
            if (validate()) {
                //$scope.waybillTrailObj.updateTime = $scope.waybillTrailObj.updateTime == ''?'':$scope.waybillTrailObj.updateTime.format("yyyy-MM-dd HH:mm:ss");
                WaybillTrailService.addWaybillTrail($scope.waybillTrailObj)
                    .success(function (result) {
                        if (result.success) {
                            $scope.routeModel($scope.waybillTrailObj.waybillId);
                            cleanTrail();
                        } else {
                            $rootScope.hycadmin.toast({
                                title: result.message,
                                timeOut: 3000
                            });
                        }
                    });
            }
        };
        // 校验在途信息
        function validate() {
            if ($scope.waybillTrailObj.provinceCode == '') {
                $rootScope.hycadmin.toast({
                    title: '板车位置省不能为空',
                    timeOut: 3000
                });
                return false;
            } else if ($scope.waybillTrailObj.cityCode == '') {
                $rootScope.hycadmin.toast({
                    title: '板车位置市不能为空',
                    timeOut: 3000
                });
                return false;
            } else if ($scope.waybillTrailObj.countyCode == '') {
                $rootScope.hycadmin.toast({
                    title: '板车位置区县不能为空',
                    timeOut: 3000
                });
                return false;
            } else if ($scope.waybillTrailObj.updateTime == '') {
                $rootScope.hycadmin.toast({
                    title: '上报日期不能为空',
                    timeOut: 3000
                });
                return false;
            } else {
                return true;
            }
        }

        // 交车窗口
        $scope.dealModel = function (waybillId, type) {
            WayBillContactsService.selectContacts({
                waybillId: waybillId,
                type: type
            }).success(function (result) {
                if (result.success) {
                    clearContact();
                    if (result.data != null) {
                        $scope.contactsObj = result.data;
                    }
                    $scope.contactsObj.waybillId = waybillId;
                    dealModal.$promise.then(dealModal.show);
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
        };
        // 交车审核窗口
        $scope.dealAuditModel = function (waybillId) {
            WaybillService.selectWaybillContact({
                id: waybillId,
                attachType: Tools.getAttachType.getDeliver(),
                type: Tools.getContactType.getReceiptPerson()
            }).success(function (result) {
                if (result.success) {
                    clearContact();
                    if (result.data != null) {
                        $scope.contactsObj = result.data;
                    }
                    $scope.contactsObj.waybillId = waybillId;
                    dealAuditModal.$promise.then(dealAuditModal.show);
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
        };

        // 交车审核
        $scope.dealAudit = function () {
            WaybillService.dealAudit({
                waybillId: $scope.contactsObj.id
            }).success(function (result) {
                if (result.success) {
                    $scope.loadData('load');
                    dealAuditModal.$promise.then(dealAuditModal.hide);
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
        };

        // 交车审核
        $scope.dealAuditRebut = function () {
            WaybillService.dealAuditRebut({
                waybillId: $scope.contactsObj.id
            }).success(function (result) {
                if (result.success) {
                    $scope.loadData('load');
                    dealAuditModal.$promise.then(dealAuditModal.hide);
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
        };

        // 上传交车照片窗口
        $scope.dealPicModel = function (waybill) {
            $scope.uploadImgs();
            $scope.waybillID = waybill.id;
            $scope.waybillDealCode = waybill.waybillCode;
            WaybillService.selectWaybillContact({
                id: waybill.id,
                attachType: Tools.getAttachType.getDeliver(),
                type: Tools.getContactType.getReceiptPerson()
            }).success(function (result) {
                if (result.success) {
                    clearContact();
                    if (result.data != null) {
                        $scope.contactsObj = result.data;
                        if ($scope.contactsObj != null) {
                            $scope.attach = $scope.contactsObj.attachs;
                            if ($scope.attach != null && $scope.attach.length > 0) {
                                angular.forEach($scope.attach, function (item) {
                                    item.picHtml = '<img src="' + item.picKey + '" style="width: 194px; height: 180px; z-index: 0;" onerror="Tools.onLoadImgErrorCallback(this, \'/image/bill-default-logo.png\')">';
                                });
                                $scope.dealBool = false;
                            } else {
                                for (var i = 0; i < 2; i++) {
                                    $scope.waybillAttach.category = Tools.getAttachType.getDeliver();
                                    if (i == 0) {
                                        $scope.waybillAttach.type = Tools.getAttachTypeEnum.getDeliverBill();
                                    } else {
                                        $scope.waybillAttach.type = Tools.getAttachTypeEnum.getDeliverPhoto();
                                    }
                                    $scope.waybillAttach.picHtml = '<img src="' + $scope.waybillAttach.picKey + '" style="width: 194px; height: 180px; z-index: 0;" onerror="Tools.onLoadImgErrorCallback(this, \'/image/+.png\')">';
                                    $scope.waybillAttach.userId = 0;
                                    $scope.attach.push($scope.waybillAttach);
                                    // 清空对象
                                    cleanAttach();
                                }
                                $scope.dealBool = true;
                            }
                        }
                        $scope.contactsObj.waybillId = waybill.id;
                        dealPicModal.$promise.then(dealPicModal.show);
                    }
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
        };
        // 保存交接单联系人数据
        $scope.saveContact = function (modal, type) {
            delete $scope.contactsObj.updateTime;
            delete $scope.contactsObj.createTime;
            $scope.contactsObj.type = type;
            WayBillContactsService.addContact($scope.contactsObj)
                .success(function (result) {
                    if (result.success) {
                        if (modal == 'dealModal') {
                            dealModal.$promise.then(dealModal.hide);
                        } else if (modal == 'liftModal') {
                            liftModal.$promise.then(liftModal.hide);
                        } else if (modal == 'departModal') {
                            departModal.$promise.then(departModal.hide);
                        }
                        $scope.loadData('load');
                        clearContact();
                    } else {
                        $rootScope.hycadmin.toast({
                            title: result.message,
                            timeOut: 3000
                        });
                    }
                });
        };

        // 清空交接单联系人数据
        function clearContact() {
            $scope.contactsObj = {
                id: '',
                waybillId: '',
                type: '',
                contact: '',
                idno: '',
                phone: '',
                licenseNumner: '',
                updateTime: '',
                createTime: ''
            };
        }

        // 调整行高度
        $scope.repeatFinish = function () {
            $timeout(function () {
                angular.element(document.getElementsByName("waybillList")).each(function (item) {
                    angular.element(this).css({
                        height: angular.element(this).parent().height() + 'px'
                    });
                    angular.element(this).find('a').css('line-height', angular.element(this).parent().height() - 14 + 'px');
                });
            }, 100);
        };

        $scope.getFile = function () {
            fileReader.readAsDataUrl($scope.file, $scope)
                .then(function (result) {
                    $scope.imageSrc = result;
                });
        };

        // 上传图片
        $scope.uploadImgs = function () {
            var uploader = $scope.uploader = null;
            QiniuService.getUploadQiniuToken()
                .success(function (result) {
                    if (result.success) {
                        // 单据照片
                        var imgKey = null;
                        var uploader = $scope.uploader = new FileUploader({
                            url: 'http://upload.qiniu.com/',
                            formData: [{
                                token: result.data
                            }],
                            queueLimit: 1,
                            autoUpload: true
                        });

                        uploader.filters.push({
                            name: 'file',
                            fn: function (item /*{File|FileLikeObject}*/, options) {
                                var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
                                return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
                            }
                        });
                        uploader.onSuccessItem = function (fileItem, response, status, headers) {
                            $rootScope.hycadmin.loading({
                                title: '数据处理中...'
                            });
                            QiniuService.getDownloadQiniuTicket({
                                key: response.key
                            }).success(function (result) {
                                if (result.success) {
                                    if ($scope.attach != null) {
                                        angular.forEach($scope.attach, function (item) {
                                            if (item.type == Tools.getAttachTypeEnum.getReceiptBill()) {
                                                item.picHtml = '<img src="' + result.data + '" style="width: 194px; height: 180px; z-index: 0;" onerror="Tools.onLoadImgErrorCallback(this, \'/image/truck-default-logo.png\')">';
                                                item.image = response.key;
                                            }
                                        });
                                    }
                                }
                            }).finally(function () {
                                $rootScope.hycadmin.loading.hide();
                            });
                        };

                        // 提车照片
                        var imgKey2 = null;
                        var uploader2 = $scope.uploader2 = new FileUploader({
                            url: 'http://upload.qiniu.com/',
                            formData: [{
                                token: result.data
                            }],
                            queueLimit: 1,
                            autoUpload: true
                        });

                        uploader2.filters.push({
                            name: 'file',
                            fn: function (item /*{File|FileLikeObject}*/, options) {
                                var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
                                return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
                            }
                        });
                        uploader2.onSuccessItem = function (fileItem, response, status, headers) {
                            $rootScope.hycadmin.loading({
                                title: '数据处理中...'
                            });
                            QiniuService.getDownloadQiniuTicket({
                                key: response.key
                            }).success(function (result) {
                                if (result.success) {
                                    if ($scope.attach != null) {
                                        angular.forEach($scope.attach, function (item) {
                                            if (item.type == Tools.getAttachTypeEnum.getReceiptPhoto()) {
                                                item.picHtml = '<img src="' + result.data + '" style="width: 194px; height: 180px; z-index: 0;" onerror="Tools.onLoadImgErrorCallback(this, \'/image/truck-default-logo.png\')">';
                                                item.image = response.key;
                                            }
                                        });
                                    }
                                }
                            }).finally(function () {
                                $rootScope.hycadmin.loading.hide();
                            });
                        };

                        // 交车单据照片
                        var imgKey3 = null;
                        var uploader3 = $scope.uploader3 = new FileUploader({
                            url: 'http://upload.qiniu.com/',
                            formData: [{
                                token: result.data
                            }],
                            queueLimit: 1,
                            autoUpload: true
                        });

                        uploader3.filters.push({
                            name: 'file',
                            fn: function (item /*{File|FileLikeObject}*/, options) {
                                var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
                                return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
                            }
                        });
                        uploader3.onSuccessItem = function (fileItem, response, status, headers) {
                            $rootScope.hycadmin.loading({
                                title: '数据处理中...'
                            });
                            QiniuService.getDownloadQiniuTicket({
                                key: response.key
                            }).success(function (result) {
                                if (result.success) {
                                    if ($scope.attach != null) {
                                        angular.forEach($scope.attach, function (item) {
                                            if (item.type == Tools.getAttachTypeEnum.getDeliverBill()) {
                                                item.picHtml = '<img src="' + result.data + '" style="width: 194px; height: 180px; z-index: 0;" onerror="Tools.onLoadImgErrorCallback(this, \'/image/truck-default-logo.png\')">';
                                                item.image = response.key;
                                            }
                                        });
                                    }
                                }
                            }).finally(function () {
                                $rootScope.hycadmin.loading.hide();
                            });
                        };


                        // 交车照片
                        var imgKey4 = null;
                        var uploader4 = $scope.uploader4 = new FileUploader({
                            url: 'http://upload.qiniu.com/',
                            formData: [{
                                token: result.data
                            }],
                            queueLimit: 1,
                            autoUpload: true
                        });

                        uploader4.filters.push({
                            name: 'file',
                            fn: function (item /*{File|FileLikeObject}*/, options) {
                                var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
                                return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
                            }
                        });
                        uploader4.onSuccessItem = function (fileItem, response, status, headers) {
                            $rootScope.hycadmin.loading({
                                title: '数据处理中...'
                            });
                            QiniuService.getDownloadQiniuTicket({
                                key: response.key
                            }).success(function (result) {
                                if (result.success) {
                                    if ($scope.attach != null) {
                                        angular.forEach($scope.attach, function (item) {
                                            if (item.type == Tools.getAttachTypeEnum.getDeliverPhoto()) {
                                                item.picHtml = '<img src="' + result.data + '" style="width: 194px; height: 180px; z-index: 0;" onerror="Tools.onLoadImgErrorCallback(this, \'/image/truck-default-logo.png\')">';
                                                item.image = response.key;
                                            }
                                        });
                                    }
                                }
                            }).finally(function () {
                                $rootScope.hycadmin.loading.hide();
                            });
                        };

                    }
                })
        };

        $scope.bool = true;

        // 保存提车照片附件
        $scope.saveLiftAttach = function (params) {
            var bool = false;
            angular.forEach($scope.attach, function (item) {
                if (!item.image && $scope.bool) {
                    $rootScope.hycadmin.toast({
                        title: '图片不能为空',
                        timeOut: 3000
                    });
                    bool = true;
                }
            });
            if (bool) {
                return;
            }
            $rootScope.hycadmin.loading({
                title: '数据处理中...'
            });
            WaybillAttachService.send({
                id: $scope.waybillID,
                attachs: JSON.stringify($scope.attach)
            }).success(function (result) {
                if (result.success) {
                    liftPicModal.$promise.then(liftPicModal.hide);
                    if (params) {
                        $scope.liftAudit();
                    } else {
                        $scope.loadData('load');
                    }
                }
            }).finally(function () {
                $rootScope.hycadmin.loading.hide();
            });
        };

        $scope.dealBool = true;

        // 保存交车照片附件
        $scope.saveDealAttach = function (params) {
            var bool = true;
            angular.forEach($scope.attach, function (item) {
                if (bool) {
                    if (!item.image && $scope.dealBool) {
                        $rootScope.hycadmin.toast({
                            title: '图片不能为空',
                            timeOut: 3000
                        });
                        bool = false;
                    }
                }
            });
            if (!bool) {
                return;
            }
            $rootScope.hycadmin.loading({
                title: '数据处理中...'
            });
            WaybillAttachService.delivery({
                id: $scope.waybillID,
                attachs: JSON.stringify($scope.attach)
            }).success(function (result) {
                if (result.success) {
                    dealPicModal.$promise.then(dealPicModal.hide);
                    if (params) {
                        $scope.dealAudit();
                    } else {
                        $scope.loadData('load');
                    }
                }
            }).finally(function () {
                $rootScope.hycadmin.loading.hide();
            });
        };
        // 修改未已支付状态
        $scope.updatePayStatus = function (waybillId) {
            $rootScope.hycadmin.loading({
                title: '数据处理中...'
            });
            WaybillService.updatePayStatus({
                waybillId: waybillId
            }).success(function (result) {
                if (result.success) {
                    $scope.loadData('load');
                    dealAuditModal.$promise.then(dealAuditModal.hide);
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            }).finally(function () {
                $rootScope.hycadmin.loading.hide();
            });
        };

        // 加载订单列表数据
        $scope.loadData('load');
        // 加载省数据
        loadProvince();

    }])

    .controller('WayBillDetailCtrl', ['$rootScope', '$scope', '$state', '$aside', 'AreaService', 'WaybillService', function ($rootScope, $scope, $state, $aside, AreaService, WaybillService) {
        var waybillId = $state.params.id;

        // 提车 交车运输方式
        $scope.trans1 = [{
            code: 0,
            name: '代驾'
        }, {
            code: 1,
            name: '小板'
        }];

        // 长途运输方式
        $scope.trans2 = [{
            code: 0,
            name: '小板'
        }, {
            code: 1,
            name: '大板'
        }];

        $scope.page = {
            pageNo: 1,
            totalPage: 0
        };
        $scope.waybillInfo = {};

        // 加载运单明细信息
        function loadWaybill() {
            WaybillService.selectById(waybillId)
                .success(function (result) {
                    if (result.success) {
                        $scope.waybillInfo = result.data;
                    } else {
                        $rootScope.hycadmin.toast({
                            title: result.message,
                            timeOut: 3000
                        });
                    }
                });
        };

        // 初始化数据
        loadWaybill();
    }])

    .directive('ngThumb', ['$window', function ($window) {
        var helper = {
            support: !!($window.FileReader && $window.CanvasRenderingContext2D),
            isFile: function (item) {
                return angular.isObject(item) && item instanceof $window.File;
            },
            isImage: function (file) {
                var type = '|' + file.type.slice(file.type.lastIndexOf('/') + 1) + '|';
                return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
            }
        };

        return {
            restrict: 'A',
            template: '<canvas/>',
            link: function (scope, element, attributes) {
                if (!helper.support) return;

                var params = scope.$eval(attributes.ngThumb);

                if (!helper.isFile(params.file)) return;
                if (!helper.isImage(params.file)) return;

                var canvas = element.find('canvas');
                var reader = new FileReader();

                reader.onload = onLoadFile;
                reader.readAsDataURL(params.file);

                function onLoadFile(event) {
                    var img = new Image();
                    img.onload = onLoadImage;
                    img.src = event.target.result;
                }

                function onLoadImage() {
                    var width = params.width || this.width / this.height * params.height;
                    var height = params.height || this.height / this.width * params.width;
                    canvas.attr({width: width, height: height});
                    canvas[0].getContext('2d').drawImage(this, 0, 0, width, height);
                }
            }
        };
    }])

    .controller('TmsWaybillPassageCtrl', ['$rootScope', '$scope', '$modal', 'WaybillService', 'WaybillLogisticsService', function ($rootScope, $scope, $modal, WaybillService, WaybillLogisticsService) {
        // 查询条件
        $scope.wayBill = {
            orderCode: '',
            phone: ''
        };

        // 数据列表
        $scope.waybillList = [];

        // 在途数据列表
        $scope.passageRouteList = [];

        var seeRouteModal = $modal({
            scope: $scope,
            title: '运单在途信息',
            placement: 'center',
            templateUrl: $rootScope.Context.path + '/templates/components/waybill-passage-view.html',
            show: false
        });

        // 当前对象
        $scope.userTruckObj = {
            pageNo: 1,
            pageSize: 10,
            loadMore: function ($event, pageNo) {
                this.pageNo = pageNo;
                if ((this.pageNo > $scope.page.totalPage)) {
                    $event.stopPropagation();
                    this.pageNo = $scope.page.totalPage;
                    return;
                } else if (this.pageNo < 1) {
                    $event.stopPropagation();
                    this.pageNo = 1;
                    return;
                }
                $scope.loadData();
            }
        };

        // 初始化数据列表
        $scope.loadData = function (params) {
            if ('query' === params) {
                $scope.userTruckObj.pageNo = 1;
                $scope.userTruckObj.pageSize = 10;
                $scope.page.pageNo = 1;
                $scope.page.totalPage = 0;
            }
            WaybillService.waybilllist({
                pageNo: $scope.userTruckObj.pageNo,
                pageSize: $scope.userTruckObj.pageSize,
                orderCode: $scope.wayBill.orderCode,
                phone: $scope.wayBill.phone
            }).success(function (result) {
                if (result.success) {
                    $scope.waybillList = result.data.dWaybillList;
                    $scope.page = result.data.page;
                    buildPage();
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
        };

        // 清空查询条件
        $scope.clearQuery = function () {
            $scope.wayBill = {
                orderCode: '',
                phone: ''
            };
            $scope.loadData('query');
        };

        function buildPage() {
            $scope.item = [];
            var end = ($scope.page.totalPage - $scope.userTruckObj.pageNo) > 5 ? ($scope.userTruckObj.pageNo == 1 ? (parseInt($scope.userTruckObj.pageNo) + 5) : (parseInt($scope.userTruckObj.pageNo) + 5)) : $scope.page.totalPage;
            var start = $scope.userTruckObj.pageNo > 5 ? ($scope.userTruckObj.pageNo == 1 ? (parseInt($scope.userTruckObj.pageNo) - 5) : (parseInt($scope.userTruckObj.pageNo) - 5)) : 1;
            for (var i = start; i <= end; i++) {
                $scope.item.push(i);
            }
        };

        $scope.showRouteModal = function (waybillId) {
            WaybillLogisticsService.list({
                waybillId: waybillId
            }).success(function (result) {
                if (result.success) {
                    $scope.passageRouteList = result.data;
                    seeRouteModal.$promise.then(seeRouteModal.show);
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
        };

        $scope.loadData('load');
    }])

    .controller('WaybillErrorCtrl', ['$rootScope', '$scope', 'WaybillErrorService', function ($rootScope, $scope, WaybillErrorService) {

        $scope.waybillError = {
            orderCode: ''
        };

        $scope.waybillErrorList = [];

        // 当前对象
        $scope.userTruckObj = {
            pageNo: 1,
            pageSize: 10,
            loadMore: function ($event, pageNo) {
                this.pageNo = pageNo;
                if ((this.pageNo > $scope.page.totalPage)) {
                    $event.stopPropagation();
                    this.pageNo = $scope.page.totalPage;
                    return;
                } else if (this.pageNo < 1) {
                    $event.stopPropagation();
                    this.pageNo = 1;
                    return;
                }
                $scope.loadData();
            }
        };

        // 初始化数据列表
        $scope.loadData = function (params) {
            if ('query' === params) {
                $scope.userTruckObj.pageNo = 1;
                $scope.userTruckObj.pageSize = 10;
                $scope.page.pageNo = 1;
                $scope.page.totalPage = 0;
            }
            WaybillErrorService.pageList({
                pageNo: $scope.userTruckObj.pageNo,
                pageSize: $scope.userTruckObj.pageSize,
                orderCode: $scope.waybillError.orderCode
            }).success(function (result) {
                if (result.success) {
                    $scope.waybillErrorList = result.data.waybillError;
                    $scope.page = result.data.page;
                    buildPage();
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
        };

        // 清空查询条件
        $scope.clearQuery = function () {
            $scope.waybillError = {
                orderCode: ''
            };
            $scope.loadData('query');
        };

        function buildPage() {
            $scope.item = [];
            var end = ($scope.page.totalPage - $scope.userTruckObj.pageNo) > 5 ? ($scope.userTruckObj.pageNo == 1 ? (parseInt($scope.userTruckObj.pageNo) + 5) : (parseInt($scope.userTruckObj.pageNo) + 5)) : $scope.page.totalPage;
            var start = $scope.userTruckObj.pageNo > 5 ? ($scope.userTruckObj.pageNo == 1 ? (parseInt($scope.userTruckObj.pageNo) - 5) : (parseInt($scope.userTruckObj.pageNo) - 5)) : 1;
            for (var i = start; i <= end; i++) {
                $scope.item.push(i);
            }
        };

        $scope.loadData('load');
    }])

    .controller('WaybillGenerateCtrl', ['$rootScope', '$scope', 'WaybillGenerateService', function ($rootScope, $scope, WaybillGenerateService) {

        $scope.waybillGenerate = {
            orderLineId: '',
            orderCode: ''
        };

        $scope.waybillGenerateList = [];

// 当前对象
        $scope.userTruckObj = {
            pageNo: 1,
            pageSize: 10,
            loadMore: function ($event, pageNo) {
                this.pageNo = pageNo;
                if ((this.pageNo > $scope.page.totalPage)) {
                    $event.stopPropagation();
                    this.pageNo = $scope.page.totalPage;
                    return;
                } else if (this.pageNo < 1) {
                    $event.stopPropagation();
                    this.pageNo = 1;
                    return;
                }
                $scope.loadData();
            }
        };

        // 初始化数据列表
        $scope.loadData = function (params) {
            if ('query' === params) {
                $scope.userTruckObj.pageNo = 1;
                $scope.userTruckObj.pageSize = 10;
                $scope.page.pageNo = 1;
                $scope.page.totalPage = 0;
            }
            WaybillGenerateService.pageList({
                pageNo: $scope.userTruckObj.pageNo,
                pageSize: $scope.userTruckObj.pageSize,
                orderLineId: $scope.waybillGenerate.orderLineId,
                orderCode: $scope.waybillGenerate.orderCode
            }).success(function (result) {
                if (result.success) {
                    $scope.waybillGenerateList = result.data.list;
                    $scope.page = result.data.page;
                    buildPage();
                } else {
                    layer.msg(result.message || "数据加载异常");
                }
            });
        };

        // 清空查询条件
        $scope.clearQuery = function () {
            $scope.waybillGenerate = {
                orderLineId: '',
                orderCode: ''
            };
            $scope.loadData('query');
        };

        function buildPage() {
            $scope.item = [];
            var end = ($scope.page.totalPage - $scope.userTruckObj.pageNo) > 5 ? ($scope.userTruckObj.pageNo == 1 ? (parseInt($scope.userTruckObj.pageNo) + 5) : (parseInt($scope.userTruckObj.pageNo) + 5)) : $scope.page.totalPage;
            var start = $scope.userTruckObj.pageNo > 5 ? ($scope.userTruckObj.pageNo == 1 ? (parseInt($scope.userTruckObj.pageNo) - 5) : (parseInt($scope.userTruckObj.pageNo) - 5)) : 1;
            for (var i = start; i <= end; i++) {
                $scope.item.push(i);
            }
        };

        $scope.resetImport = function (item) {
            if (item.orderId == '') {
                layer.msg("重新导入订单标识不能为空");
                return false;
            }
            WaybillGenerateService.regenerate({
                ids: item.orderId
            }).success(function (result) {
                if (result.success) {
                    $scope.loadData('load');
                } else {
                    layer.msg(result.message || "重新导入订单异常");
                }
            });
        };

        $scope.loadData('load');

    }])

    .controller('WaybillAbandonedCtrl', ['$rootScope', '$scope', 'WaybillAbandonedService', function ($rootScope, $scope, WaybillAbandonedService) {

        $scope.waybillList = [];

        $scope.queryObj = {
            orderCode: '',
            abandonedCode: '',
            abandonedReason: '',
            gmtCreate: ''
        };

        $scope.userTruckObj = {
            pageNo: 1,
            pageSize: 10,
            loadMore: function ($event, pageNo) {
                this.pageNo = pageNo;
                if ((this.pageNo > $scope.page.totalPage)) {
                    $event.stopPropagation();
                    this.pageNo = $scope.page.totalPage;
                    return;
                } else if (this.pageNo < 1) {
                    $event.stopPropagation();
                    this.pageNo = 1;
                    return;
                }
                $scope.loadData();
            }
        };

        // 初始化数据列表
        $scope.loadData = function (params) {
            if ('query' === params) {
                $scope.userTruckObj.pageNo = 1;
                $scope.userTruckObj.pageSize = 10;
                $scope.page.pageNo = 1;
                $scope.page.totalPage = 0;
            }
            WaybillAbandonedService.pageList({
                pageNo: $scope.userTruckObj.pageNo,
                pageSize: $scope.userTruckObj.pageSize,
                orderCode: $scope.queryObj.orderCode,
                abandonedCode: $scope.queryObj.abandonedCode,
                abandonedReason: $scope.queryObj.abandonedReason
            }).success(function (result) {
                if (result.success) {
                    $scope.waybillList = result.data.list;
                    $scope.page = result.data.page;
                    buildPage();
                } else {
                    layer.msg(result.message || "数据加载异常");
                }
            });
        };

        // 清空查询条件
        $scope.clearQuery = function () {
            $scope.queryObj = {
                orderCode: '',
                abandonedCode: '',
                abandonedReason: '',
                gmtCreate: ''
            };
            $scope.loadData('query');
        };

        function buildPage() {
            $scope.item = [];
            var end = ($scope.page.totalPage - $scope.userTruckObj.pageNo) > 5 ? ($scope.userTruckObj.pageNo == 1 ? (parseInt($scope.userTruckObj.pageNo) + 5) : (parseInt($scope.userTruckObj.pageNo) + 5)) : $scope.page.totalPage;
            var start = $scope.userTruckObj.pageNo > 5 ? ($scope.userTruckObj.pageNo == 1 ? (parseInt($scope.userTruckObj.pageNo) - 5) : (parseInt($scope.userTruckObj.pageNo) - 5)) : 1;
            for (var i = start; i <= end; i++) {
                $scope.item.push(i);
            }
        };

        $scope.loadData('load');
    }])